package cn.huiyunche.driver.controller;

import cn.huiyunche.base.service.interfaces.DWaybillService;
import cn.huiyunche.base.service.interfaces.TmsQueueService;
import cn.huiyunche.base.service.interfaces.UserService;
import cn.huiyunche.base.service.model.BLicenseType;
import cn.huiyunche.base.service.model.DWaybill;
import cn.huiyunche.base.service.vo.PageVo;
import cn.huiyunche.base.service.vo.Result;
import cn.huiyunche.base.service.vo.TmsDriverVo;
import cn.huiyunche.driver.service.TmsCustomerService;
import cn.huiyunche.driver.service.TmsDDeliveryAuditService;
import cn.huiyunche.driver.service.TmsQueueDimensionService;
import cn.huiyunche.driver.service.form.TmsDDeliveryAuditForm;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 中联客服控制器
 *
 * @author hdy [Tuffy]
 */
@Controller
@RequestMapping("/zl")
public class TmsCustomerController {
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(TmsAdminController.class);

    @Autowired
    private TmsCustomerService tmsCustomerService = null;

    @Autowired
    private TmsQueueService tmsQueueService = null;

    @Autowired
    private TmsQueueDimensionService tmsQueueDimensionService;
    @Autowired
    private DWaybillService dWaybillService;

    @Autowired
    private UserService userService = null;

    @Autowired
    private TmsDDeliveryAuditService tmsDDeliveryAuditService;


    private UserService getUserService() {
        return this.userService;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String init() {
        return "tms/login";
    }

    /**
     * 登录
     *
     * @param phone    手机号
     * @param password 密码
     * @return 登录信息
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Result<String> login(HttpServletRequest request, String phone, String password) {
        return this.tmsCustomerService.login(request, phone, password);
    }

    /**
     * 退出登录
     *
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    @ResponseBody
    public Result<String> logout(HttpServletRequest request) {
        return this.tmsCustomerService.logout(request);
    }

    /**
     * 首页
     *
     * @return 首页信息
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView index(HttpServletRequest request) {
        return this.tmsCustomerService.index(request);
    }

    /**
     * 开通账号
     *
     * @param phone 司机手机号
     * @return
     */
    @RequestMapping(value = "/open", method = RequestMethod.POST)
    @ResponseBody
    public Result<String> openAccount(HttpServletRequest request, @RequestParam("phone") String phone) {
        return this.tmsCustomerService.openAccount(request, phone);
    }

    /**
     * 添加司机
     *
     * @param tdv 司机表单
     * @return 结果集
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Result<String> addDriver(@Valid TmsDriverVo tdv, BindingResult br) {
        if (br.hasErrors()) {
            String errorMessage = br.getAllErrors().get(0).getDefaultMessage();
            throw new IllegalArgumentException(errorMessage);
        }
        return this.tmsCustomerService.addDriver(tdv);
    }

    /**
     * 获取证件类型列表
     *
     * @return
     */
    @RequestMapping(value = "/license", method = RequestMethod.GET)
    @ResponseBody
    public Result<List<BLicenseType>> getBLicenseList() {
        return this.tmsCustomerService.getBLicenseList();
    }

    /**
     * 修改用户手机号，并开通
     *
     * @param request 请求
     * @param idCard  身份证
     * @param phone   手机号
     * @return 结果集
     */
    @RequestMapping(value = "/exchange", method = RequestMethod.POST)
    @ResponseBody
    public Result<String> exchangeUser(HttpServletRequest request, String idCard, String phone) {
        return this.tmsCustomerService.exchangeAccount(request, idCard, phone);
    }

    /**
     * 通过身份证号码获取用户信息
     *
     * @param request 请求
     * @param idCard  身份证
     * @return 结果集
     */
    @RequestMapping(value = "/idno", method = RequestMethod.GET)
    @ResponseBody
    public Result<String> getAccountByIdNo(HttpServletRequest request, String idCard) {
        return this.tmsCustomerService.getAccountByIdNo(request, idCard);
    }

    /**
     * 禁用账号
     *
     * @param phone 司机手机号
     * @return
     */
    @RequestMapping(value = "/disable", method = RequestMethod.POST)
    @ResponseBody
    public Result<String> disableAccount(HttpServletRequest request, @RequestParam("phone") String phone) {
        return this.tmsCustomerService.disableAccount(request, phone);
    }

    /**
     * Cancel user waybill result.
     *
     * @param orderCode the order code
     * @return the result
     */
    @RequestMapping(value = "/cancel", method = RequestMethod.POST)
    public
    @ResponseBody
    Result<String> cancelUserWaybill(HttpServletRequest request, @RequestParam("orderCode") String orderCode, String cancelreason, String cancelflag) {
        return tmsCustomerService.cancelDWaybillWithUser(request, orderCode, cancelreason, cancelflag);
    }

    /**
     * 置顶订单数据
     *
     * @param orderCodes 订单编码
     * @return 结果集
     */
    @RequestMapping(value = "/reset", method = RequestMethod.POST)
    @ResponseBody
    public Result<String> resetQueueOrder(String orderCodes) throws Exception {
        return this.tmsQueueService.resetQueueOrder(orderCodes);
    }

    /**
     * 异常订单
     *
     * @param request    请求
     * @param orderCodes 订单对象
     * @return 结果集
     */
    @RequestMapping(value = "/exception", method = RequestMethod.POST)
    @ResponseBody
    public Result<String> exceptionOrderList(HttpServletRequest request, String orderCodes) {
        return this.tmsCustomerService.exceptionConfirmResult(request, orderCodes);
    }

    /**
     * 获取队列订单信息
     *
     * @param request 请求
     * @return 结果集
     */
    @RequestMapping(value = "/orders", method = RequestMethod.GET)
    @ResponseBody
    public Result<Object> queueOrderList(HttpServletRequest request) throws Exception {
        return this.tmsCustomerService.queueOrderList(request);
    }

    /**
     * 获取队列司机信息
     *
     * @param request 请求
     * @return 结果集
     */
    @RequestMapping(value = "/drivers", method = RequestMethod.GET)
    @ResponseBody
    public Result<Object> queueDriverList(HttpServletRequest request) throws Exception {
        return this.tmsCustomerService.queueDriverList(request);
    }

    /**
     * 回单
     *
     * @param request    请求
     * @param phone      手机号
     * @param orderCodes 订单号
     * @return 结果集
     */
    @RequestMapping(value = "/receipt", method = RequestMethod.POST)
    @ResponseBody
    public Result<String> receipt(HttpServletRequest request, String phone, String orderCodes) throws Exception {
        return this.tmsCustomerService.receipt(request, phone, orderCodes);
    }

    /**
     * 退单列表
     *
     * @param request
     * @param orderCode
     * @return
     */
    @RequestMapping(value = "/chargeback", method = RequestMethod.GET)
    @ResponseBody
    public Result<Object> calcenList(HttpServletRequest request, String orderCode) {
        return this.tmsCustomerService.calcenList(request, orderCode);
    }

    /**
     * 订单重新入队
     *
     * @param request
     * @param orderCode
     * @return
     */
    @RequestMapping(value = "/addordertoredis", method = RequestMethod.POST)
    @ResponseBody
    public Result<String> addOrderToRedis(HttpServletRequest request, String orderCode) throws Exception {
        return this.tmsCustomerService.addOrderToRedis(request, orderCode);
    }

    /**
     * 根据订单号查询订单信息
     *
     * @param request
     * @param orderCode
     * @return
     */
    @RequestMapping(value = "/queryorder", method = RequestMethod.GET)
    @ResponseBody
    public Result<Object> queryOrder(HttpServletRequest request, String orderCode) {
        return this.tmsCustomerService.queryOrder(request, orderCode);
    }

    /**
     * Select Users By Phone
     *
     * @param request
     * @param phone
     * @return
     */
    @RequestMapping(value = "/userList", method = RequestMethod.GET)
    public
    @ResponseBody
    Result<Object> userList(HttpServletRequest request, String phone) {
        return this.tmsCustomerService.userList(request, phone);
    }

    /**
     * 头像采集
     *
     * @param id
     * @param pic
     * @return
     */
    @RequestMapping(value = "/updatepic", method = RequestMethod.POST)
    public
    @ResponseBody
    Result<Object> updatePic(Long id, String pic) {
        Result<Object> result = new Result<>(true, null, "上传成功");
        result.setData(this.getUserService().updatePicById(id, pic));
        return result;
    }

    /**
     * 指定司机接单
     * @return
     */
    @RequestMapping(value = "/designateDrivers", method = RequestMethod.POST)
    @ResponseBody
    public Result<Object> designateDrivers(@RequestParam("phone") String phone,@RequestParam("orderCode")String orderCode) throws Exception {
        LOGGER.info(" designateDrivers params : {}.", phone,orderCode);
        Result<Object> result = new Result<>(true, "派单成功");
        try {
            tmsQueueDimensionService.designateDrivers(phone,orderCode);
        }catch (BusinessException e){
            LOGGER.error("designateDrivers error : {}",e);
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        } catch (Exception e) {
            LOGGER.error("designateDrivers error : {}",e);
            result.setSuccess(false);
            result.setMessage("手动派单失败");
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 分页查询手动派单列表
     * @return
     */
    @RequestMapping(value = "/sendOrders", method = RequestMethod.POST)
    @ResponseBody
    public Result<Object> sendOrders(PageVo pageVo,String orderCode,String beginDate, String endDate,String vin,String destProvince,String destCity,String orderStatus) throws Exception {
        LOGGER.info(" sendOrders params : {}.", pageVo);
        Result<Object> result = new Result<>(true, "查询成功");
        try {
            Map<String, Object> stringObjectMap = tmsCustomerService.chargebackPage(pageVo, orderCode,beginDate,endDate,vin,destProvince,destCity,orderStatus);
            result.setData(stringObjectMap);
        } catch (Exception e) {
            LOGGER.error("sendOrders error : {}",e);
            result.setSuccess(false);
            result.setMessage("查询失败");
        }
        return result;
    }
    /**
     * 重新计算价格推送tms
     * @param orderCode
     * @return
     **/
    @RequestMapping(value = "/accountingPrice", method = RequestMethod.POST)
    public
    @ResponseBody
    Result<Object> accountingPrice( String orderCode,String reason) {
        Result<Object> result = new Result<>(true, "计算成功");
        try{
            dWaybillService.recalculateAndUpdate(orderCode,reason);
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }
    @RequestMapping(value = "/getWaybillByOrderCode",method = RequestMethod.POST)
    public
    @ResponseBody
    Result<List<DWaybill>> getWaybillByOrderCode(String orderCode){
        Result<List<DWaybill>> result = new Result<>(true, "查询成功");
        try {
            result.setData(dWaybillService.getWaybill(orderCode));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }
    /**
     * 订单导出
     * @return
     */
    @RequestMapping(value = "/ordersExport", method = RequestMethod.POST)
    @ResponseBody
    public Result<Object> ordersExport(String orderCode,String beginDate, String endDate,String vin,
                                       String destProvince,String destCity,String orderStatus,HttpServletRequest request,HttpServletResponse response) throws Exception {
        LOGGER.info(" sendOrders params : {}.", orderCode);
        Result<Object> result = new Result<>(true, "导出成功");
        try {
            Map<String, Object> stringObjectMap = tmsCustomerService.ordersExport(orderCode,beginDate,endDate,vin,destProvince,destCity,orderStatus);
            result.setData(stringObjectMap);
        } catch (Exception e) {
            LOGGER.error("sendOrders error : {}",e);
            result.setSuccess(false);
            result.setMessage("导出失败");
        }
        return result;
//        String excelName;
//        if ("1".equals(orderStatus)|| StringUtils.isBlank(orderStatus)){
//            excelName="未安排订单";
//        }else{
//            excelName="已安排订单";
//        }
//        ExcelExport.exprotBefore(request,response,excelName);
//        OutputStream fOut = null;
//        try {
//            String[] titile={"派单时间","指令号","车架号","起始地省","起始地市","目的地省","目的地市","车辆信息",};
//            List<String[]> listData = tmsCustomerService.ordersExport(orderCode,beginDate,endDate,vin,destProvince,destCity,orderStatus);
//            Boolean[] isdigit={null,null,null,null,null,null,null,null};
//            int[] columnWidth={40,28,28,30,35,35,28,100 };
//            HSSFWorkbook workbook =ExcelExport.export(excelName, titile,listData,columnWidth,isdigit, "");
//            fOut = response.getOutputStream();
//            workbook.write(fOut);
//        } catch (UnsupportedEncodingException e1) {
//            LOGGER.error("export carinsurancedetails failure reason 1 :"+e1.getMessage());
//            e1.getMessage();
//        } catch (Exception e) {
//            LOGGER.error("export carinsurancedetails failure reason 2 :"+e.getMessage());
//            e.getMessage();
//        } finally {
//            try {
//                fOut.flush();
//                fOut.close();
//            } catch (IOException e) {
//                e.getMessage();
//            }
//        }
    }

    @RequestMapping(value = "/orderExport", method = RequestMethod.POST)
    @ResponseBody
    public Result<Object> orderExport(String orderCode,String beginDate, String endDate,String vin,
                                       String destProvince,String destCity,String orderStatus,HttpServletRequest request,HttpServletResponse response) throws Exception {
        LOGGER.info(" sendOrders params : {}.", orderCode);
        Result<Object> result = new Result<>(true, "导出成功");
        try {
            Map<String, Object> stringObjectMap = tmsCustomerService.orderExport(orderCode, beginDate, endDate, vin, destProvince, destCity, orderStatus);
            result.setData(stringObjectMap);
        } catch (Exception e) {
            LOGGER.error("sendOrders error : {}", e);
            result.setSuccess(false);
            result.setMessage("导出失败");
        }
        return result;
    }

    /**
     * 获取司机人送司机
     * @return
     */
    @RequestMapping(value = "/peopleSendDriver", method = RequestMethod.GET)
    @ResponseBody
    public Result<Object> peopleSendDriver(String name,String tmsDriverNo) throws Exception {
        LOGGER.info(" peopleSendDriver params : {}.", name);
        Result<Object> result = new Result<>(true, "查询成功");
        try {
            result.setData(tmsCustomerService.peopleSendDriver(name,tmsDriverNo));
        } catch (Exception e) {
            LOGGER.error("peopleSendDriver error : {}",e);
            result.setSuccess(false);
            result.setMessage("查询失败");
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 重新入队
     *
     * @param orderCode
     * @return
     */
    @RequestMapping(value = "/backToTheTeam", method = RequestMethod.POST)
    @ResponseBody
    public Result<String> backToTheTeam( String orderCode) throws Exception {
        LOGGER.info(" backToTheTeam params : {}.",orderCode);
        Result<String> result = new Result<>(true, "重新入队成功");
        try {
             tmsCustomerService.backToTheTeam(orderCode);
        }catch (BusinessException e){
            LOGGER.error("backToTheTeam error : {}",e);
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        } catch (Exception e) {
            LOGGER.error("designateDrivers error : {}",e);
            result.setSuccess(false);
            result.setMessage("重新入队失败");
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 分页查询 退单列表
     * @return
     */
    @RequestMapping(value = "/chargebackList", method = RequestMethod.POST)
    @ResponseBody
    public Result<Object> chargebackList(PageVo pageVo,String orderCode,String beginDate, String endDate,String vin,String isQueryHistory) throws Exception {
        LOGGER.info(" chargebackList params : {}.", pageVo);
        Result<Object> result = new Result<>(true, "查询成功");
        try {
            Map<String, Object> stringObjectMap = tmsCustomerService.chargebackList(pageVo, orderCode,beginDate,endDate,vin,isQueryHistory);
            result.setData(stringObjectMap);
        } catch (Exception e) {
            LOGGER.error("chargebackList error : {}",e);
            result.setSuccess(false);
            result.setMessage("查询失败");
        }
        return result;
    }


    /**
     * 导出退单列表
     * @return
     */
    @RequestMapping(value = "/exportChargebackList", method = RequestMethod.POST)
    @ResponseBody
    public Result<Object> exportChargebackList(String orderCode,String beginDate,String endDate,String vin,String isQueryHistory) throws Exception {
        LOGGER.info(" exportChargebackList params : {}.",orderCode );
        Result<Object> result = new Result<>(true, "导出成功");
        try {
            Map<String, Object> stringObjectMap = tmsCustomerService.exportChargebackList(orderCode, beginDate, endDate, vin, isQueryHistory);
            result.setData(stringObjectMap);
        } catch (Exception e) {
            LOGGER.error("exportChargebackList error : {}",e);
            result.setSuccess(false);
            result.setMessage("导出失败");
        }
        return result;
    }
    /**
     * 分页查询 订单状态
     * @return
     */
    @RequestMapping(value = "/orderStatusList", method = RequestMethod.POST)
    @ResponseBody
    public Result<Object> orderStatusList(PageVo pageVo,String orderCode,String beginDate, String endDate,String vin,String orderStatus) throws Exception {
        LOGGER.info(" orderStatusList params : {}.", pageVo);
        Result<Object> result = new Result<>(true, "查询成功");
        try {
            Map<String, Object> stringObjectMap = tmsCustomerService.orderStatusList(pageVo, orderCode,beginDate,endDate,vin,orderStatus);
            result.setData(stringObjectMap);
        } catch (BusinessException e) {
            LOGGER.error("orderStatusList error : {}",e);
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        } catch (Exception e) {
            LOGGER.error("orderStatusList error : {}",e);
            result.setSuccess(false);
            result.setMessage("查询失败");
        }
        return result;
    }

    /**
     * 更新 订单状态
     * @return
     */
    @RequestMapping(value = "/updateOrderStatus", method = RequestMethod.POST)
    @ResponseBody
    public Result<Object> updateOrderStatus(Integer orderStatus,String ids) throws Exception {
        LOGGER.info(" updateOrderStatus params id:{},orderStatus:{}",ids,orderStatus);
        Result<Object> result = new Result<>(true, "更新成功");
        try {
            tmsCustomerService.updateOrderStatus(orderStatus,ids);
        } catch (BusinessException e) {
            LOGGER.error("updateOrderStatus error : {}",e);
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        } catch (Exception e) {
            LOGGER.error("updateOrderStatus error : {}",e);
            result.setSuccess(false);
            result.setMessage("更新失败");
        }
        return result;
    }
    /**
     * @return
     * @Title: 设置运单审核
     * @Description: TODO
     * @return: Result<T>
     */
    @RequestMapping(value = "/checkDelivery", method = RequestMethod.POST)
    public
    @ResponseBody
    Result<T> checkDelivery(TmsDDeliveryAuditForm form) {
        Result<T> result = new Result<>(true, "运单审核操作成功");
        try {
            tmsDDeliveryAuditService.save(form);
        } catch (Exception e) {
            LOGGER.error("confirmResult error : {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }
}
